﻿using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;

namespace SilverQuery
{
	public static class ExtensionMethods
	{
		/// <summary>
		/// Emulates the jQuery $.each function.
		/// </summary>
		public static void each<T>(this IEnumerable<T> collection, Action<int, T> action)
		{
			for (int i=0; i<collection.Count(); i++)
	      action(i, collection.ElementAt(i));
		}

		/// <summary>
		/// Concactenate each element in the collection into a single delimited string.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="collection"></param>
		/// <param name="delimiter"></param>
		/// <returns></returns>
		public static string concat<T>(this IEnumerable<T> collection, char delimiter)
		{
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < collection.Count(); i++)
			{
				if (i > 0)
					sb.Append(delimiter);
				sb.Append((object)collection.ElementAt(i));
			}
			return sb.ToString();
		}

		/// <summary>
		/// Emulates the jQuery.map function. Translate all items in a collection to another collection of items.
		/// </summary>
		/// <typeparam name="T1"></typeparam>
		/// <typeparam name="T2"></typeparam>
		/// <param name="collection"></param>
		/// <param name="function"></param>
		/// <returns></returns>
		public static IEnumerable<T2> map<T1, T2>(this IEnumerable<T1> collection, Func<int, T1, T2> func)
		{
			var output = new List<T2>();
			for (int i=0; i<collection.Count(); i++)
			{
				T2 translated = func(i, (T1)collection.ElementAt(i));
				if (translated != null)
					output.Add(translated);
			}
			return output;
		}
	}
}